package com.earstep.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
	/**
	 * 线程池对象
	 */
	private static ThreadPoolExecutor threadPool = null;
	/**
	 * 保留的线程池大小
	 */
	private static Integer corePoolSize;
	/**
	 * 线程池最大
	 */
	private static Integer maximumPoolSize;
	/**
	 * 空闲线程的超时时间
	 */
	private static long keepAliveTime;
	/**
	 * 存放任务的队列
	 */
	private static BlockingQueue<Runnable> workQueue;
	/**
	 * 队列存放任务最大量
	 */
	private static Integer workQueueSize;

	private ThreadPool() {
	}

	/**
	 * 单例模式 获取线程池对象
	 */
	private static ThreadPoolExecutor getInstance() {
		if (threadPool == null) {
			threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
					keepAliveTime, TimeUnit.MILLISECONDS, workQueue);
		}
		return threadPool;
	}

	/**
	 * 根据ThreadPool.properties初始化成员变量
	 * 
	 * @throws Exception
	 */
	public static void init(ThreadJsonModel model) throws Exception {
		corePoolSize = model.getCorePoolSize() == null ? 3 : model
				.getCorePoolSize();
		maximumPoolSize = model.getMaximumPoolSize() == null ? 10 : model
				.getMaximumPoolSize();
		keepAliveTime = model.getKeepAliveTime() < 0 ? 10000 : model
				.getKeepAliveTime();
		workQueueSize = model.getWorkQueueSize() == null ? 100 : model
				.getWorkQueueSize();
		workQueue = new ArrayBlockingQueue<Runnable>(workQueueSize, true);
	}

	/**
	 * 加入一个任务 分配给线程池
	 * 
	 * @param threadPoolCallback
	 */
	public static void queueItem(Runnable threadPoolCallback) {
		if (null == threadPool) {
			getInstance();
		}
		threadPool.execute(threadPoolCallback);
	}

	/**
	 * 从任务队列中删除某项
	 */
	public static void remove(Runnable task) {
		threadPool.remove(task);
	}

	/**
	 * 关闭线程池
	 */
	public static void shutdown() {
		getInstance().shutdown();
	}
}
